package com.wupo.gen;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Scanner;

public class WuPoGenApplication {

    /**
     * 读取控制台内容
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(tip);
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args){

        /**
         * 获取mp-gen.properties配置信息
         */
        final ResourceBundle rb = ResourceBundle.getBundle("mp-gen");

        /**
         * 代码生成器
         */
        AutoGenerator autoGenerator = new AutoGenerator();

        /**
         * 全局配置
         */
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setOutputDir(rb.getString("gc.genDir")+"/src/main/java");
        globalConfig.setAuthor(rb.getString("gc.author"));
        globalConfig.setOpen(false);
        globalConfig.setFileOverride(true);
        globalConfig.setSwagger2(true);
        globalConfig.setBaseResultMap(true);
        globalConfig.setBaseColumnList(true);
        globalConfig.setEnableCache(true);
        globalConfig.setDateType(DateType.ONLY_DATE); //时间类型对应策略，默认值TIME_PACK
        globalConfig.setIdType(IdType.NONE); //主键策略，默认，如果未设置主键策略（null），默认根据雪花算法生成
        autoGenerator.setGlobalConfig(globalConfig);

        /**
         * 数据源配置
         */
        DataSourceConfig dataSourceConfig = new DataSourceConfig();
        dataSourceConfig.setDbType(DbType.MYSQL);
        dataSourceConfig.setDbQuery(new MySqlQuery());
        dataSourceConfig.setTypeConvert(new MySqlTypeConvert());
        dataSourceConfig.setUrl(rb.getString("jdbc.url"));
        dataSourceConfig.setDriverName(rb.getString("jdbc.driverName"));
        dataSourceConfig.setUsername(rb.getString("jdbc.username"));
        dataSourceConfig.setPassword(rb.getString("jdbc.password"));
        autoGenerator.setDataSource(dataSourceConfig);

        /**
         * 生成包配置
         */
        PackageConfig packageConfig = new PackageConfig();
        //手动输入模块名
        String pack = rb.getString("package.baseParent");
        //packageConfig.setParent(pack + scanner("请输入子包名"));
        //packageConfig.setModuleName(scanner("请输入模块名"));
        //autoGenerator.setPackageInfo(packageConfig);
        autoGenerator.setPackageInfo(packageConfig.setParent(pack));

        /**
         * 模板配置
         */
        TemplateConfig templateConfig = new TemplateConfig();
        templateConfig.setXml(null);
        templateConfig.setEntity("/vm/entity.java.vm");
        templateConfig.setService("/vm/service.java.vm");
        templateConfig.setServiceImpl("/vm/serviceImpl.java.vm");
        templateConfig.setController("/vm/controller.java.vm");
        templateConfig.setMapper("/vm/mapper.java.vm");
        autoGenerator.setTemplate(templateConfig);
        autoGenerator.setTemplateEngine(new VelocityTemplateEngine());

        /**
         * 注入自定义配置
         */
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
            }
        };
        // 修改xml文件生成到src/main/resources下
        String customXmlTemplate = "/vm/mapper.xml.vm";
        List<FileOutConfig> outConfigList = new ArrayList<>();
        outConfigList.add(new FileOutConfig(customXmlTemplate) {
            @Override
            public String outputFile(TableInfo tableInfo) {
//                return rb.getString("gc.genDir") + "/src/main/resources/mappers/"+ packageConfig.getModuleName()
                return rb.getString("gc.genDir") + "/src/main/resources/mappers/" + "/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(outConfigList);
        autoGenerator.setCfg(cfg);

        /**
         * 数据库表生成策略配置
         */
        StrategyConfig strategyConfig = new StrategyConfig();
        strategyConfig.setNaming(NamingStrategy.underline_to_camel);// 表映射驼峰命名
        strategyConfig.setColumnNaming(NamingStrategy.underline_to_camel);// 字段映射驼峰命名
        strategyConfig.setEntityLombokModel(true); // 是否使用lombok，默认false
        strategyConfig.setRestControllerStyle(true); // 默认false
        strategyConfig.setEntitySerialVersionUID(true); // 默认true
        //多个表名用“,”号隔开,不设置参数默认所有表
        //strategyConfig.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategyConfig.setInclude(scanner("请输入表名"));// 针对单个表
        strategyConfig.setControllerMappingHyphenStyle(false);// 驼峰转连字符,默认false
        strategyConfig.setEntityTableFieldAnnotationEnable(true); // 生成实体时，生成字段注解，默认false
        strategyConfig.setLogicDeleteFieldName("status");// 逻辑删除字段名称
//        strategyConfig.setTableFillList();//设置自动填充字段
        //表前缀处理后续完成
        //String table_pre = scanner("请输入表前缀");
        //strategyConfig.setTablePrefix(table_pre);
        //将数据库表名为 user_info 格式的转换为 UserInfo 命名
        strategyConfig.setTablePrefix(packageConfig.getModuleName() + "_");
        //strategyConfig.setSuperEntityClass(BaseEntity.class);
        autoGenerator.setStrategy(strategyConfig);

        /**
         * 生成代码
         */
        System.out.println("===================== Wupo Code Generator ==================");
        autoGenerator.execute();
        System.out.println("================= Wupo Code Generator Execute Complete ==================");

    }
}
